# -*- coding:utf-8 -*-

import socket, struct, hmac
from server import cache
from multiprocessing import Process, Pool
from server.util import sqlBuild, stringUtil


class bellMode(object):
    reids_test = cache.re()

    def __init__(self, db, re):
        self.db, self.conn = db, re
        self.key = "2e0160e078aa4b925e62b20610378253"
        self.lcList, self.seList = set(), set()

        # con_parm = ("192.168.1.5", 2111)
        con_parm = ("127.0.0.1", 2111)
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect(con_parm)

    @reids_test.re_batch
    def zadd_task(self, tasks, base_point, pipe=None):
        for each in tasks:
            com, count = each[:]
            baId = com.split(",")[0]
            ss = stringUtil.redis_key_name(baId, "ss")
            base_point.add(baId)
            self.conn.zadd(ss, com, count)


    """ 任务分为：
    群发任务(seon/seof)
    单发任务(lnon/lnof)
    放弃治疗(bmon/bmof)
    """
    def messageHandler(self, tasks, **kwargs):
        base_point = set()  # 待发送基站列表
        bell_command = 'bell'

        self.zadd_task(tasks, base_point)  # 将任务存入redis

        for baId in base_point:  # 发送bell指令
            lb = stringUtil.redis_key_name(baId)
            bel = stringUtil.redis_key_name(baId, "be")

            bel_num, k = self.conn.get(bel), None
            k = int(bel_num) if bel_num else None

            base_status = self.conn.lindex(lb, 1)  # 当前状态

            if k != 0 and (k % 5 == 0):
                self.conn.lset(lb, 1, bell_command)  # 将状态更改为bell
                message = baId + ',' + bell_command
                self.sendMessage(message)
            elif k > 90:
                self.conn.lset(lb, 1, 91)

            self.conn.set(bel, k + 1)
            # if base_status is not None and len(base_status) == 1 or len(base_status) == 2:  # 正常执行状态的位数
            #     self.conn.lset(lb, 1, bell_command)  # 将状态更改为bell
            #     message = baId + ',' + bell_command
            #     self.sendMessage(message)
            # else:
            #     pass

        # 杀死链接
        catCar = self.conn.smembers("cop")  # 所有已存在任务
        self.conn.delete("cop")
        for corpse in catCar:
            self.sendMessage(corpse)

    def sendMessage(self, sendData):  # 发送信息
        # 加密
        password = stringUtil.get_hmac(self.key, sendData)
        sendData = sendData + "," + password

        pack = stringUtil.length_pack(sendData)

        self.s.send(pack)
